// pages/Slling_book/Slling_book.js
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        sellbook_cart: [], //卖书栏数据
        sendList:[],//发送给后端的卖书栏数据
        book: [], //售卖书本的信息
        book_ISBN: "", //卖书ISBN数据
        totalprice: 0, //总价
        selectAll: "circle", //是否全选
        num: 0, //商品数量
        showPage: false,
        inputvalue: "", //输入框的值
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var that = this
    },
    //   获取需要售卖的书籍信息
    // 1 把获取到的ISBN码给予book_ISBN
    // 2 在书籍数据库里用扫码得到的ISBN码作为索引去查询书籍
    // 3 调用书籍页面填写函数write_book填写内容
    // 4 把获取到的书籍信息存入数组
    // 5 把数组的数据动态绑定页面
    // 扫码获取ISBN
    getsellcarts() {
        var that = this
        wx.scanCode({
            success: function (res) {
                that.setData({
                    book_ISBN: res.result
                })
                that.co_book_info()
            }
        })

    },
    //携带信息转跳书籍详情页面
    async gotobookinfor() {
        var that = this
        return new Promise((resolve, reject) => {
            wx.navigateTo({
                url: '/pages/book_infor/book_infor',
                events: {
                    //接收被打开页面的数据
                    acceptDataFromOpenedPage: function (data) {
                        if(data.data.url!==""){
                          that.setData({
                              sellbook_cart: that.data.sellbook_cart.concat(data.data)
                          })
                        }
                    },
                },
                success(res) {
                    res.eventChannel.emit(
                        'bookinforPage', {
                            data: that.data.book[0]
                        }
                    )
                    resolve(that.data.book[0])
                    // console.log(that.data.book)
                },
                fail(err) {
                    console.log('失败')
                    reject(err)
                }
            })
        })
    },


    //根据ISBN在数据库中搜索书籍
     async co_book_info() {
       wx.showLoading({
         title: '卖力搜索中...',
       })
       const bookInfo=await wx.p.request({
         url: app.globalData.url+'/silling_book/selectISBN',
         data:{
           isbn:this.data.book_ISBN
         }
       })
       if(bookInfo.data.code==1){
        this.setData({
          book:bookInfo.data.data
        })
        this.gotobookinfor()
       }else{
         wx.showToast({
           title: bookInfo.data.msg,
         })
       }
       wx.hideLoading()
    },

    Sell() {
      var that = this;
      if (that.data.sendList.length==0) {
        wx.showToast({
          title: '未出售任何商品',
          icon:"error"
        })
      }else{
        wx.showLoading({
          title: '出售中',
          mask: true
        });
        wx.request({
          url: app.globalData.url + "/Silling_book/sell",
          method: "POST",
          data: {
            sellBookList: this.data.sendList,
            sellTotal: this.data.num,
            uid: app.globalData.userInfo.uid
          },
          success: function(res) {
            console.log(res.data);
            if (res.data.code === 1) {
              var updatedList = that.data.sendList.filter(obj => obj.select !== "success");
              that.setData({
                sendList: [],
                sellbook_cart: updatedList,
                num: 0,
                totalprice: 0
              });
      
              // 出售成功后延迟2秒关闭加载框
              setTimeout(function() {
                wx.hideLoading();
                wx.showToast({
                  title: '出售成功',
                  icon: 'success',
                  duration: 500,
                  mask: true
                });
              }, 1000);
            } else {
              wx.hideLoading();
              wx.showToast({
                title: '出售失败，请重试',
                icon: 'none',
                duration: 2000,
                mask: true
              });
            }
          },
          fail: function(err) {
            wx.hideLoading();
            console.log(err);
          }
        });
      }
      
    },



    // 弹出层
    tap: function () {
        // var that = this
        // console.log("运行成功")
        this.setData({
            showPage: true
        });
    },
    
    // 取消按钮
    cancal_tap() {
        this.setData({
            showPage: false
        })
    },
    
    // 确定按钮
    // 1 获取输入框中的ISBN码
    // 2 把获取到的ISBN码拿去云数据库中搜索
    expInput() {
        var that = this
        // console.log(this.data.inputvalue)
        this.setData({
            book_ISBN: that.data.inputvalue,
            showPage: false,
            inputvalue: ''
        })
        this.co_book_info()
    },
    //获取输入框中的内容
    take_isbn: function (e) {
        var that = this
        that.data.inputvalue = ''
        this.setData({
            inputvalue: e.detail.value
        })
    },
    // 复选框
    onChange(e) {
      console.log(e)
        var that = this
        var index = e.currentTarget.dataset.index
        var select = e.currentTarget.dataset.select
        var newList = that.data.sellbook_cart
        //检测newList是否含有index字段，没有的话添加
        if (!newList[index].hasOwnProperty('index')) {
          newList[index].index = index;
        }
        console.log(newList)
        // console.log(select)
        if (select == "circle") {
            var stype = "success"
            //加进数组
            newList[index].index = index;
            that.setData({
              sendList: that.data.sendList.concat(newList[index])
            });


        } else {
            var stype = "circle"
            //移除数组
            that.setData({
              sendList: that.data.sendList.filter(obj => obj.index !== index)
            });
        }
        // console.log(newList)
        newList[index].select = stype
        that.setData({
            sellbook_cart: newList
        })
        this.countprice()
        this.countNum()
    },
    // 价格计算方法
    countprice() {
        var that = this
        var newList = that.data.sellbook_cart
        var newCount = 0
        for (var i = 0; i < newList.length; i++) {
            if (newList[i].select == "success") {
                newCount += newList[i].num * newList[i].price
            }
        }
        that.setData({
            totalprice: newCount
        })
    },
    // 数量计算方法
    countNum() {
        var that = this
        var newList = that.data.sellbook_cart
        var allNum = 0
        for (var i = 0; i < newList.length; i++) {
            if (newList[i].select == "success") {
                allNum += parseInt(newList[i].num)
            }
        }
        that.setData({
            num: allNum
        })
    },
    //全选
    allselect(e) {
        var that = this
        var newList = that.data.sellbook_cart
        var allSelect = e.currentTarget.dataset.select
        if (allSelect == "circle") {
          that.setData({
            sendList:newList
          })
            for (var i = 0; i < newList.length; i++) {
                newList[i].select = "success"
            }
            var select = "success"
        } else {
          that.setData({
            sendList:[]
          })
            for (var i = 0; i < newList.length; i++) {
                newList[i].select = "circle"
            }
            var select = "circle"
        }
        that.setData({
            sellbook_cart: newList,
            selectAll: select
        })
        this.countprice()
        this.countNum()
    },

    // 出售书籍
    // 上传售卖书籍信息
    upload() {
        var that = this
        var newlist = that.data.sellbook_cart //存放需要卖出的书籍信息
        var bookcaselist = that.data.bookcase_num
        
        for (var i = 0; i < newlist.length; i++) {
            if (newlist[i].select == "success") {
                //这是用户sellbook_list
                newlist.splice((i - 1), 1)
            }
        }
        that.setData({
            sellbook_cart: newlist,
            selectAll: 'circle',
            num: 0,
            totalprice: 0
        })
        // console.log(bookcaselist.caes_num)
    },
  
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})